/**
 * 所有子管理器的管理器
 */
cc.Class({
    extends: cc.Component,

    properties: {
        /**
         * 显示子域的图片
         */
        openDataDisplay: cc.Sprite,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.socketOpened = false;
        this.unconnectedMsg = "";
    },

    start () {
        //面板字典
        this._panelDic = new Array();
        this._menuManager = this.registManager("MenuPanel", "MenuManager");
        this._inviteRoomManager = this.registManager("InviteRoomPanel", "InviteRoomManager");
        this._gameManager = this.registManager("GamePanel", "GameManager");
        this._matchingManager = this.registManager("MatchingPanel", "MatchingManager");
        //当前所在的面板
        this._currentPanel = this._menuManager;
        this._currentPanel.node.active = true;
        this.msgHandler();

        
        this.connectSocket();
        this.getSelfInfo();
        this.isFromFriendRoom();

        this.rankTex = new cc.Texture2D();
    },

    update (dt) {
        this.updaetSubDomainCanvas();
    },

    /**
     * 更新子域的信息显示
     */
    updaetSubDomainCanvas () {
        if (!this.rankTex || !CC_WECHATGAME) return;
        var openDataContext = wx.getOpenDataContext();
        var sharedCanvas = openDataContext.canvas;
        this.rankTex.initWithElement(sharedCanvas);
        this.rankTex.handleLoadedTexture();
        this.openDataDisplay.node.setContentSize(cc.director.getVisibleSize());
        this.openDataDisplay.spriteFrame = new cc.SpriteFrame(this.rankTex);
    },

    /**
     * 注册一个管理器
     * @param {string} nodeName 节点名称
     * @param {string} managerName 管理器名称
     * @returns 管理器变量
     */
    registManager (nodeName, managerName) {
        var manager = this.node.getChildByName(nodeName).getComponent(managerName);
        manager.mainManager = this;
        this._panelDic[nodeName] = manager;
        //默认隐藏
        manager.node.active = false;
        return manager;
    },

    /**
     * 转到对应的面板上
     * @param {string} dstPanel 目标面板名称
     */
    changePanel (dstPanel) {
        this._currentPanel.node.active = false;

        this._currentPanel = this._panelDic[dstPanel];
        this._currentPanel.node.active = true;
        //初始化
        this._currentPanel.init();
    },

    /**
     * 发起网络请求
     */
    connectSocket () {
        if (!CC_WECHATGAME) return;
        // wx.connectSocket({
        //     url: 'ws://localhost:3653',
        // });
        
        wx.showLoading({
            title: '网络连接中',
        })
        
        wx.connectSocket({
            url: 'ws://132.232.111.177:3653',
        });
    },

    /**
     * 获取用户信息
     */
    getSelfInfo () {
        if (!CC_WECHATGAME) return;
        var self = this;
        wx.login({
            success: function(res) {
                if(res.code){
                    console.log(res.code)
                    //发送请求
                    wx.request({
                        url: 'https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code', //接口地址
                        data: {
                            js_code: res.code,
                            appid:"wx02fc763fd70050f3",
                            secret:"93c688636f3c50d815991ae878021366",
                        },
                        success: function (res) {
                            console.log(res.data)
                            GameData.OpenID = res.data.openid;
                            //有需要进入的房间
                            if (self.waitToEnter) {
                                self.enterRoom(self.waitToEnter);
                            }
                        }
                    })
                }
                else{
                    console.log("登录失败")
                }
            }
        });
    },

    /**
     * 保证连接成功后发送数据
     * @param {struct} msg 消息
     */
    sendSocketMessage (msg) {
        if (CC_WECHATGAME) {
            var str = JSON.stringify(msg);
            this.sendStringMessage(str);
        }
    },

    /**
     * 保证连接成功后发送数据
     */
    sendStringMessage (str) {
        if (this.socketOpened) { // socketOpened变量在wx.onSocketOpen时设置为true
            wx.sendSocketMessage({
                data: str
            });
        } else { // 发送的时候，链接还没建立
            this.unconnectedMsg = str;
        }
    },

    /**
     * 发送未连接好的消息
     */
    sendUnconnectMsg () {

    },

    /**
     * 接收到消息的处理
     */
    msgHandler () {
        if (!CC_WECHATGAME) return;
        //事件监听
        var self = this;
        wx.onSocketOpen(function(res){
            console.log('websocket opened.');
            self.socketOpened = true;
            //把队列中的数据全部发送
            // if (self.unconnectedMsg != ""){
            //     wx.sendSocketMessage({
            //         data: self.unconnectedMsg
            //     });
            // }
            wx.hideLoading();
            if (self.waitToEnter) {
                self.enterRoom(self.waitToEnter);
            }
        });
        wx.onSocketError(function(res){
            console.log('websocket fail.');
            wx.hideLoading();
        });
        var self = this;
        wx.onSocketMessage(function(res){
            //转成JSON格式
            var str =  String.fromCharCode.apply(null, new Uint8Array(res.data));
            var jsonData = JSON.parse(str);
            console.log(jsonData);
            var jsonType = self.getMsgType(jsonData);
            switch (jsonType) {
                case "RoomInfo":
                    //离开房间后不再处理
                    if (GameData.IsInRoom) {
                        self._inviteRoomManager.setRoomInfo(jsonData.RoomInfo);
                    }
                    break;
                case "GameStart":
                    //收到游戏开始命令
                    this.changePanel('GamePanel');
                    break;
            }
        });
    },

    /**
     * 判断获取的JSON数据类型
     * 强制转成字符串判断
     * @param {JSON} json 数据
     * @returns JSON数据的类型
     */
    getMsgType (json) {
        var splits = JSON.stringify(json).split('"');
        if (splits.length < 2) return "error";
        return splits[1];
    },

    /**
     * 向子域发送消息
     * @param {JSON} msg 消息
     */
    postToOpenData (msg) {
        if (!CC_WECHATGAME) return;
        wx.postMessage(msg);
    },

    /**
     * 判断是否来自好友房间的邀请
     * @returns 是否好友邀请进入
     */
    isFromFriendRoom () {
        if (!CC_WECHATGAME) return;
        //游戏已经打开的检测
        var self = this;
        wx.onShow(function(res){
            console.log('onShow');
            if (res.query.Share == "Battle") {
                //是从好友的邀请房间进入的
                self.enterRoom(res.query.RoomNo);
            }
        });
        //刚进入游戏的检测
        var LaunchOption = wx.getLaunchOptionsSync();
        console.log(LaunchOption);
        this._waitToEnterRoom = false;
        if (LaunchOption.query.Share == "Battle") {
            //是从好友的邀请房间进入的
            this._waitToEnterRoom = true;
            this._waitRoomNo = LaunchOption.query.RoomNo;
            
        }
    },

    /**
     * 通过点击进入房间的创建房间号
     * 将创建好的房间号传递给房间管理器
     */
    createRoom () {
        var myDate = new Date();
        //当前时间
        var hour = myDate.getHours();
        var min = myDate.getMinutes();
        var sec = myDate.getSeconds();
        var mSec = myDate.getMilliseconds();
        var randomNum = Math.floor(cc.random0To1() * 1000);
        var roomNo = "FriendRoom" + hour + ":" + min + ":" + sec + ":" + mSec + "" + randomNum;
        console.log("创建房间" + roomNo);
        this._inviteRoomManager.recieveRoomNo(roomNo);
        this._inviteRoomManager.setPlayer(0, GameData.OpenID);
        this.sendSocketMessage({EnterRoom: {
            RoomNo: roomNo,
            Pos: 0,
            OpenId: GameData.OpenID,
        }});
    },

    /**
     * 通过好友的邀请进入的房间
     * @param {string} roomNo 房间号
     */
    enterRoom (roomNo) {
        //可能出现还没有ID的情况
        if (GameData.OpenID != "") {
            this._inviteRoomManager.recieveRoomNo(roomNo);
            this.changePanel('InviteRoomPanel');
            this.sendSocketMessage({EnterRoom: {
                RoomNo: roomNo,
                Pos: 1,
                OpenId: GameData.OpenID,
            }});
        }
        else{
            this.waitToEnter = roomNo;
        }
    },

    /**
     * 子域绘制不显示
     */
    closeOpenDataCanvas () {
        this.postToOpenData({
            message: 'Close'
        });
    },


});
